package mya.mes.mdc.logic.dispatch.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import mya.common.jpa.context.NoLoginLogic;
import mya.common.jpa.context.ServiceContext;
import mya.common.model.json.JsonHelper;
import mya.common.util.Utils;
import mya.mes.mdc.logic.dispatch.build.DispatchContentBuilder;
import mya.mes.mdc.logic.dispatch.executor.DispatchExecutor;
import mya.mes.mdc.logic.mqtt.PlcTagResult;
import mya.mes.mdc.logic.tag.PlcTagCache;
import mya.mes.mdc.model.alarm.MdcAlarm;
import mya.mes.mdc.model.dispatch.MdcDispatchContent;
import mya.mes.mdc.model.system.RegularReminders;
import mya.mes.mdc.queries.alarm.MdcAlarmQuery;
import mya.mes.mdc.constant.Sysconstant;
import mya.mes.mdc.websocket.MdcBroadcast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定期提醒
 */
class SysRemindTimerTask implements Runnable {

    @Override
    public void run() {

        List<RegularReminders> regularReminderses = PlcTagCache.getInstance().getRegularReminderses();
        if (regularReminderses != null && regularReminderses.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String current = simpleDateFormat.format(new Date());
            for (RegularReminders reminders : regularReminderses) {
                Boolean result = false;
                if (Sysconstant.remindType_1.equals(reminders.getRemindType())) {
                    if (reminders.getNextRemindTime() != null && !"".equals(reminders.getNextRemindTime())) {
                        if (current.equals(reminders.getNextRemindTime())) {
                            System.out.println("发送提醒");
                            result = true;
                        }
                    } else {
                        Long remindTime = null;
                        try {
                            remindTime = simpleDateFormat.parse(reminders.getRemindTime()).getTime();
                        } catch (ParseException e) {

                        }
                        if (current.equals(reminders.getRemindTime())) {
                            System.out.println("发送提醒");
                            result = true;
                        } else if (remindTime < System.currentTimeMillis()) {
                            Long space = System.currentTimeMillis() - remindTime;
                            if (space % (24 * 60 * 60 * 1000) == 0) {
                                result = true;
                            }
                        }
                    }

                    if (result) {
                        Long nextTime = System.currentTimeMillis() + 24 * 60 * 60 * 1000;
                        String next = simpleDateFormat.format(new Date(nextTime));
                        reminders.setNextRemindTime(next);
                    }

                } else if (Sysconstant.remindType_2.equals(reminders.getRemindType())) {

                    if (reminders.getNextRemindTime() != null && !"".equals(reminders.getNextRemindTime())) {
                        if (current.equals(reminders.getNextRemindTime())) {
                            System.out.println("发送提醒");
                            result = true;
                        }
                    } else {
                        String start = reminders.getStartTime();
                        String end = reminders.getEndTime();
                        if (start != null && !"".equals(start) && end != null && !"".equals(end)) {
                            try {
                                Long startTime = simpleDateFormat.parse(start).getTime();
                                Long endTime = simpleDateFormat.parse(end).getTime();
                                if (current.equals(start)) {
                                    System.out.println("发送提醒");
                                    if ((startTime + Integer.parseInt(reminders.getCycleInterval()) <= endTime)) {
                                        result = true;
                                    }
                                } else if (startTime < System.currentTimeMillis()) {
                                    Long space = System.currentTimeMillis() - startTime;
                                    if (space % Integer.parseInt(reminders.getCycleInterval()) == 0) {
                                        result = true;
                                    }
                                }

                            } catch (ParseException e) {

                            }
                        }
                    }
                    if (result) {
                        Long nextTime = System.currentTimeMillis() + Integer.parseInt(reminders.getCycleInterval()) * 60 * 1000;
                        String next = simpleDateFormat.format(new Date(nextTime));
                        reminders.setNextRemindTime(next);
                    }
                }

                if (result) {
                    ObjectWriter remindResultWriter = JsonHelper.objectMapper.writerFor(RegularReminders.class);
                    String jsonStr = null;

                    try {
                        jsonStr = remindResultWriter.writeValueAsString(reminders);
                    } catch (JsonProcessingException e) {

                    }
                    jsonStr = "{\"reminds\":[" + jsonStr + "]}";
                    MdcBroadcast.broadcast(jsonStr);
                }
            }
        }
    }


    private void updateFlag(ServiceContext context, List<MdcAlarm> toPerson, List<MdcAlarm> toManager) {
        if (toPerson != null && toPerson.size() > 0) {
            for (MdcAlarm alarm : toPerson) {
                alarm.setHasSentToPerson(Boolean.TRUE);
            }
        }
        if (toManager != null && toManager.size() > 0) {
            for (MdcAlarm alarm : toManager) {
                alarm.setHasSentToManager(Boolean.TRUE);
            }
        }
    }

    private List<MdcAlarm> getOrQuery(ServiceContext context, long current,
                                      final boolean fromDb) throws Exception {
        List<MdcAlarm> list;
        if (fromDb) {
            list = MdcAlarmQuery.loadNeedDispatch(context, current);
        } else {
            list = AlarmDispatchManager.getInstance().getAlarmCurrent().cloneAlarmList();
        }
        return list;
    }

    private List<MdcAlarm> filterToPerson(List<MdcAlarm> list, long current) {
        List<MdcAlarm> toPerson = null;
        for (MdcAlarm mdcAlarm : list) {
            if (mdcAlarm.getTimeWaitToPerson() == null) {
                continue;
            }
            if (mdcAlarm.hasSentToPerson != null && mdcAlarm.hasSentToPerson) {
                //已经发送
                continue;
            }
            if (mdcAlarm.getTimeWaitToPerson() < current) {
                if (toPerson == null) {
                    toPerson = new ArrayList<>();
                }
                toPerson.add(mdcAlarm);
            }
        }
        return toPerson;
    }


    private List<MdcAlarm> filterToManager(List<MdcAlarm> list, long current) {
        List<MdcAlarm> toManager = null;
        for (MdcAlarm mdcAlarm : list) {
            if (mdcAlarm.getTimeWaitToManager() == null) {
                continue;
            }
            if (mdcAlarm.hasSentToManager != null && mdcAlarm.hasSentToManager) {
                //已经发送
                continue;
            }
            if (mdcAlarm.getTimeWaitToManager() < current) {
                if (toManager == null) {
                    toManager = new ArrayList<>();
                }
                toManager.add(mdcAlarm);
            }
        }
        return toManager;
    }

}
